﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Reflection;

namespace VSSTQH
{
    public static class CollectionExtensions<T>
    {
        #region Converting ObjectArray to Datatable
        public static DataTable ConvertToDataTable(IEnumerable<T> array, string tableName)
        {
            PropertyInfo[] properties = typeof(T).GetProperties();
            DataTable dt = CreateDataTable(properties, tableName);
            if (array.Count() != 0)
            {
                foreach (T o in array)
                    FillData(properties, dt, o);
            }
            return dt;
        }

        private static DataTable CreateDataTable(PropertyInfo[] properties, string tableName)
        {
            DataTable dt = new DataTable(tableName);
            DataColumn dc = null;
            foreach (PropertyInfo pi in properties)
            {
                if (pi.PropertyType.Name != typeof(Nullable<>).Name)
                {
                    dc = new DataColumn();
                    dc.ColumnName = pi.Name;
                    dc.DataType = pi.PropertyType;
                    dt.Columns.Add(dc);
                }
            }
            return dt;
        }

        private static void FillData(PropertyInfo[] properties, DataTable dt, Object o)
        {
            try
            {

                DataRow dr = dt.NewRow();
                foreach (PropertyInfo pi in properties)
                {
                    if (pi.PropertyType.Name != typeof(Nullable<>).Name)
                    {
                        dr[pi.Name] = pi.GetValue(o, null);
                    }
                }
                dt.Rows.Add(dr);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

        }

        #endregion
    }
}
